<?php

/**
 * choice actions.
 *
 * @package    samsung
 * @subpackage choice
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class choiceActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeList(sfWebRequest $request) {
    if (!$request->hasParameter('question_id')) {
      $this->forward404();
    }
    $this->choices = CHOICETable::getInstance()->getByQuestionId($request->getParameter('question_id'), true);
    $question    = QUESTIONTable::getInstance()->find($request->getParameter('question_id'));
    $this->questionName    = $question->getQuestion();
    $this->questionId = $request->getParameter('question_id');
  }

  public function executeAdd(sfWebRequest $request) {
    $errorCollector = array();
    $this->form = new ChoiceForm();
    if ($request->hasParameter('question_id')) {
      $this->form->setDefault(ChoiceForm::FIELD_QUESTION, $request->getParameter('question_id'));
    }
    $this->isEdit = false;

    if ($request->hasParameter('id')) {
      $this->isEdit = true;
      $choice = CHOICETable::getInstance()->find($request->getParameter('id'));
      $this->form->populateData($choice);
      if (!$choice instanceof CHOICE) {
        $this->isEdit = false;
      }
    }
    try {
      if ($request->isMethod('post')) {
        $formData = $request->getParameter(ChoiceForm::FORM_NAME);
        $this->form->bind($formData);

        if ($this->form->isValid()) {
          if (!$this->isEdit) {
            $choice = new CHOICE();
            $lineNo = CHOICETable::getInstance()->getMaxId() + 1;
            $choice->setLineNo($lineNo);
          }
          $choice->setQuestionId($formData[ChoiceForm::FIELD_QUESTION]);
          $choice->setChoice($formData[ChoiceForm::FIELD_CHOICE]);
          $choice->setIsCorrect($formData[ChoiceForm::FIELD_IS_CORRECT]);
          $choice->save();

          $this->redirect('@choice-list?question_id='.$formData[ChoiceForm::FIELD_QUESTION]);
        }
      }
    } catch (Exception $e) {
      $errorCollector[] = 'Internal error!.. Please try again';
    }
    $this->errorCollector = $errorCollector;
  }

  public function executeDelete(sfWebRequest $request) {
    $choice = CHOICETable::getInstance()->find($request->getParameter('id'));
    if (!$choice instanceof CHOICE) {
      $this->forward404();
    }
    try {
      $choice->setIsActive(Constants::STATUS_DELETED);
      $choice->save();

      $this->redirect('@choice-list?question_id='.$choice->getQuestionId());
    } catch (Exception $e) {
      
    }
  }
}
